<template>
  <div class="fee-rules-container">
    <div class="header">
      <h2>费用规则管理</h2>
      <el-button type="primary" @click="handleAdd">新增费用规则</el-button>
    </div>

    <!-- 费用规则列表 -->
    <el-table :data="feeRules" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="type" label="规则类型" width="120">
        <template #default="{ row }">
          {{ getRuleTypeName(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="规则名称" width="150" />
      <el-table-column prop="rate" label="费率" width="120">
        <template #default="{ row }"> {{ row.rate }}% </template>
      </el-table-column>
      <el-table-column prop="startDate" label="开始时间" width="180" />
      <el-table-column prop="endDate" label="结束时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button type="danger" link @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增费用规则' : '编辑费用规则'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择规则类型">
            <el-option label="骑手抽成" value="rider" />
            <el-option label="商家抽成" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="费率" prop="rate">
          <el-input-number
            v-model="form.rate"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.1"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getFeeRules,
  addFeeRule,
  updateFeeRule,
  deleteFeeRule,
} from "@/api/fee";

// 表格数据
const feeRules = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const formRef = ref(null);
const form = reactive({
  type: "",
  name: "",
  rate: 0,
  dateRange: [],
  status: 1,
});

// 表单验证规则
const rules = {
  type: [{ required: true, message: "请选择规则类型", trigger: "change" }],
  name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  rate: [{ required: true, message: "请输入费率", trigger: "blur" }],
  dateRange: [{ required: true, message: "请选择时间范围", trigger: "change" }],
};

// 获取规则类型名称
const getRuleTypeName = (type) => {
  const typeMap = {
    rider: "骑手抽成",
    merchant: "商家抽成",
  };
  return typeMap[type] || type;
};

// 获取费用规则列表
const getFeeRulesList = async () => {
  try {
    const res = await getFeeRules({
      page: currentPage.value,
      pageSize: pageSize.value,
    });
    feeRules.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error("获取费用规则列表失败");
  }
};

// 新增费用规则
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  Object.assign(form, {
    type: "",
    name: "",
    rate: 0,
    dateRange: [],
    status: 1,
  });
};

// 编辑费用规则
const handleEdit = (row) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  Object.assign(form, {
    ...row,
    dateRange: [row.startDate, row.endDate],
  });
};

// 删除费用规则
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该费用规则吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await deleteFeeRule(row.id);
      ElMessage.success("删除成功");
      getFeeRulesList();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...form,
          startDate: form.dateRange[0],
          endDate: form.dateRange[1],
        };
        delete data.dateRange;

        if (dialogType.value === "add") {
          await addFeeRule(data);
          ElMessage.success("新增成功");
        } else {
          await updateFeeRule(data.id, data);
          ElMessage.success("编辑成功");
        }
        dialogVisible.value = false;
        getFeeRulesList();
      } catch (error) {
        ElMessage.error(dialogType.value === "add" ? "新增失败" : "编辑失败");
      }
    }
  });
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val;
  getFeeRulesList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getFeeRulesList();
};

// 初始化
onMounted(() => {
  getFeeRulesList();
});
</script>

<style scoped>
.fee-rules-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.unit {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
